package com.forlove.app.manager;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;

import com.forlove.app.common.utils.AppPreferenceHelper;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.qselect.friend.widget.contact.ChineseToEnglish;
import com.forlove.app.qselect.login.entity.ContactsInfoEntity;
import com.forlove.app.qselect.login.entity.ContactsInfoEntityList;
import com.forlove.app.qselect.login.entity.UserEntity;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 用户手机联系人管理类
 * Created by yjl on 2017/10/9.
 */

public class ContactsManager {


    /**
     * 检查读取联系人权限
     */
    public static List<ContactsInfoEntity> checkContectPermission(Activity context) {
        List<ContactsInfoEntity> contactList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(context, new String[]{android.Manifest.permission.READ_CONTACTS}, 1);
            return contactList;
        } else {
            return getContectInfo(context);
        }
    }

    /**
     * 只获取通讯录中是手机号的好友，会排除不是手机号的好友
     *
     * @param context
     * @return
     */
    public static List<ContactsInfoEntity> getContectInfo(Context context) {
        List<ContactsInfoEntity> contactList = new ArrayList<>();
        try {
            Uri contactUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
            Cursor cursor = context.getContentResolver().query(contactUri,
                    new String[]{"display_name", "sort_key", "contact_id", "data1"},
                    null, null, "sort_key");
            String contactName;
            String contactNumber;
            String contactSortKey;
            int contactId;
            UserEntity userEntity = UserManager.getUesrInfo(context);
            while (cursor.moveToNext()) {
                contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                contactNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
                        .replaceAll(" ", "")
                        .replaceAll("\\s*", "");

                if ((userEntity != null
                        && !TextUtils.isEmpty(userEntity.userMobile)
                        && contactNumber.equals(userEntity.userMobile))
                        || !StringUtils.isMobile(contactNumber)) {
                    continue;
                }
                contactId = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                contactSortKey = getSortkey(cursor.getString(1));
                ContactsInfoEntity contactsInfo = new ContactsInfoEntity(contactName, contactNumber, contactSortKey, contactId);
                if (contactNumber != null)
                    contactList.add(contactsInfo);
            }
            cursor.close();//使用完后一定要将cursor关闭，不然会造成内存泄露等问题

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            context = null;
        }
//        for (ContactsInfoEntity contactsInfoEntity : contactList) {
//            LogUtil.e("yjl", "name:" + contactsInfoEntity.getName() + "    mobile:" + contactsInfoEntity.getNumber());
//        }
        return contactList;
    }

    private static String getSortkey(String sortKeyString) {
        if (!StringUtils.isNotEmpty(sortKeyString)) {
            return "#";
        }
        String pingyin = ChineseToEnglish.getFullSpell(sortKeyString);
        String key = pingyin.substring(0, 1).toUpperCase();
        if (key.matches("[A-Z]")) {
            return key;
        } else
            return "#";   //获取sort key的首个字符，如果是英文字母就直接返回，否则返回#。
    }

    public static List<ContactsInfoEntity> getContectInfoLimit(Context context) {
        List<ContactsInfoEntity> contactList = null;
        try {
            Uri contactUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
            Cursor cursor = context.getContentResolver().query(contactUri,
                    new String[]{"display_name", "sort_key", "contact_id", "data1"},
                    null, null, "sort_key");
            String contactName;
            String contactNumber;
            String contactSortKey;
            int contactId;
            UserEntity userEntity = UserManager.getUesrInfo(context);
            if (cursor != null) {
                //TODO 防止小米通讯录问题
                contactList = new ArrayList<>();
            }
            while (cursor.moveToNext()) {
                contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                contactNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
                        .replaceAll(" ", "")
                        .replaceAll("\\s*", "");

                if ((userEntity != null
                        && !TextUtils.isEmpty(userEntity.userMobile)
                        && contactNumber.equals(userEntity.userMobile))
                        || !StringUtils.isMobile(contactNumber)) {
                    continue;
                }
                contactId = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                contactSortKey = getSortkey(cursor.getString(1));
                ContactsInfoEntity contactsInfo = new ContactsInfoEntity(contactName, contactNumber, contactSortKey, contactId);
                if (contactNumber != null)
                    if (contactList == null) {
                        contactList = new ArrayList<>();
                    }
                contactList.add(contactsInfo);
            }
            cursor.close();//使用完后一定要将cursor关闭，不然会造成内存泄露等问题

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            context = null;
        }
        return contactList;
    }


    public static void saveContactsFriend(Context mContext, List<ContactsInfoEntity> contactsInfoEntities) {
        ContactsInfoEntityList contactsInfoEntityList = new ContactsInfoEntityList();
        contactsInfoEntityList.contactsInfoEntities.addAll(contactsInfoEntities);
        AppPreferenceHelper.getInstance(mContext).putString(PreferenceKeys.CONTACTS_FRIEND, contactsInfoEntityList.serializeToString());
    }

    public static String getSaveContactsFriend(Context mContext) {

        return AppPreferenceHelper.getInstance(mContext).getString(PreferenceKeys.CONTACTS_FRIEND, "");
    }


    /**
     * 随机指定范围内N个不重复的数
     * 在初始化的无重复待选数组中随机产生一个数放入结果中，
     * 将待选数组被随机到的数，用待选数组(len-1)下标对应的数替换
     * 然后从len-2里随机产生下一个随机数，如此类推
     *
     * @param max 指定范围最大值
     * @param min 指定范围最小值
     * @param n   随机数个数
     * @return int[] 随机数结果集
     */
    public static int[] randomArray(int min, int max, int n) {
        int len = max - min + 1;

        if (max < min || n > len) {
            return null;
        }

        //初始化给定范围的待选数组
        int[] source = new int[len];
        for (int i = min; i < min + len; i++) {
            source[i - min] = i;
        }

        int[] result = new int[n];
        Random rd = new Random();
        int index = 0;
        for (int i = 0; i < result.length; i++) {
            //待选数组0到(len-2)随机一个下标
            index = Math.abs(rd.nextInt() % len--);
            //将随机到的数放入结果集
            result[i] = source[index];
            //将待选数组中被随机到的数，用待选数组(len-1)下标对应的数替换
            source[index] = source[len];
        }
        return result;
    }


//    //读取通讯录的全部的联系人
////需要先在raw_contact表中遍历id，并根据id到data表中获取数据
//    public static List<ContactsInfoEntity> testReadAll(Context context) {
//        List<ContactsInfoEntity> contactList = new ArrayList<>();
//        try {
//            Uri uri = Uri.parse("content://com.android.contacts/contacts"); //访问raw_contacts表
//            ContentResolver resolver = context.getContentResolver();
//            UserEntity userEntity = UserManager.getUesrInfo(context);
//            //获得_id属性
//            Cursor cursor = resolver.query(uri, new String[]{ContactsContract.RawContacts.Data._ID}, null, null, null);
//            int i = 0;
//            while (cursor.moveToNext()) {
//                i++;
//                //获得id并且在data中寻找数据
//                int id = cursor.getInt(0);
//                String contactName = "";
//                String contactNumber = "";
//                String contactSortKey = getSortkey(cursor.getString(1));
//                ;
//                int contactId = id;
//                Uri uri2 = Uri.parse("content://com.android.contacts/contacts/" + id + "/data");
//                //data1存储各个记录的总数据，mimetype存放记录的类型，如电话、email等
//                Cursor cursor2 = resolver.query(uri2, new String[]{ContactsContract.RawContacts.Data.DATA1,
//                        ContactsContract.RawContacts.Data.MIMETYPE}, null, null, null);
//                try {
//                    while (cursor2.moveToNext()) {
//                        String data = cursor2.getString(cursor2.getColumnIndex("data1"));
//                        if (cursor2.getString(cursor2.getColumnIndex("mimetype")).equals("vnd.android.cursor.item/name")) {       //如果是名字
//                            contactName = data;
//                            LogUtil.e("yjl", "name:" + data);
//                        } else if (cursor2.getString(cursor2.getColumnIndex("mimetype")).equals("vnd.android.cursor.item/phone_v2")) {  //如果是电话
//                            contactNumber = data.replaceAll(" ", "").replaceAll("\\s*", "");
//                            LogUtil.e("yjl", "mobile:" + data);
//                        }
//                    }
//                    cursor2.close();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                } finally {
//                    cursor2.close();
//                }
//                if ((userEntity != null && !TextUtils.isEmpty(userEntity.userMobile)
//                        && contactNumber.equals(userEntity.userMobile)) || !StringUtils.isMobile(contactNumber)) {
//                    continue;
//                }
//                ContactsInfoEntity contactsInfo = new ContactsInfoEntity(contactName, contactNumber, contactSortKey, contactId);
//                contactList.add(contactsInfo);
//            }
//            cursor.close();
//            LogUtil.e("yjl", "i:" + i);
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            context = null;
//        }
//
//        return contactList;
//    }
}
